package org.vincen.helloworld.jaxb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.joda.time.DateTime;

public class BookMain {

	private static final String bookXML = "bookstore_jaxb.xml";

	public static void main(String[] args) throws JAXBException,
			FileNotFoundException {
		ArrayList<Book> bookList = new ArrayList<Book>();
		// create books
		Book book1 = new Book();
		book1.setBookName("spring攻略");
		book1.setAuthor("Gary Mak");
		book1.setPrice(89.00f);
		book1.setLanguage("English");
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("translator", "丁雪丰");
		map1.put("executor", "陈兴路");
		book1.setEditors(map1);
		DateTime dt1 = new DateTime(2009, 8, 1, 11, 20);
		book1.setPublishDate(dt1.toDate());
		bookList.add(book1);

		Book book2 = new Book();
		book2.setBookName("java并发编程实战");
		book2.setAuthor("Brian Goetz");
		book2.setPrice(69.00f);
		book2.setLanguage("Chinese");
		Map<String, String> map2 = new HashMap<String, String>();
		map2.put("translator", "童云兰");
		map2.put("executor", "关敏");
		book2.setEditors(map2);
		DateTime dt2 = new DateTime(2012, 2, 1, 23, 15);
		book1.setPublishDate(dt2.toDate());
		bookList.add(book2);

		// create bookstore, assigning book
		BookStore bookstore = new BookStore();
		bookstore.setName("Fraport Bookstore");
		bookstore.setLocation("Frankfurt Airport");
		bookstore.setBookList(bookList);
		
		JAXBHelper helper = new JAXBHelper(BookStore.class);
		Marshaller m = helper.buildMarshaller();
		// write to System.out
		m.marshal(bookstore, System.out);
		// print the xml
		 System.out.println();
		// write to file
		m.marshal(bookstore, new File(bookXML));
		System.out.println("create file successd");
		
		JAXBContext context = JAXBContext.newInstance(BookStore.class);
		Unmarshaller um = context.createUnmarshaller();
		BookStore bookstore2 = (BookStore) um
				.unmarshal(new FileReader(bookXML));
		ArrayList<Book> list = bookstore2.getBookList();
		for (Book b : list) {
			System.out.println("Book: " + b.getBookName() + " from "
					+ b.getAuthor());
		}

	}
}
